package com.ruike.alisurface.project_DaTi;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.TextView;

import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.project_DaTi.bean.AnswerQuestionBean;
import com.ruike.alisurface.project_DaTi.bean.QuestionBean;
import com.ruike.alisurface.project_DaTi.adapter.QuestionOptionListAdapter;
import com.ruike.alisurface.project_DaTi.bean.ResultAnswerBean;
import com.ruike.alisurface.project_DaTi.http.QuestionHttpTools;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020/07/21 021 05:25 下午
 * Description: 答题界面
 */
public class AnswerQuestionActivity extends BaseAty {

    @BindView(R.id.answerQuestion_questionTime_tv)
    TextView questionTimeTv; // 每道题的倒计时
    @BindView(R.id.answerQuestion_questionNumber_tv)
    TextView questionNumberTv; // 第X题
    @BindView(R.id.answerQuestion_questionType_tv)
    TextView questionTypeTv; // 题目类型
    @BindView(R.id.answerQuestion_questionStem_tv)
    TextView questionStemTv; // 题目
    @BindView(R.id.answerQuestion_questionOption_recv)
    RecyclerView questionOptionRecv; // 选项列表
    @BindView(R.id.answerQuestion_nextQuestion_btn)
    Button nextQuestionBtn; // 下一题按钮，最后一道题设置为“完成” 这个View只是显示文字，点击事件的View是：answerQuestion_nextQuestion_rlayout

    // 获取到的题目列表
    List<QuestionBean> questionList;

    int questionTime = 60; // 每道题题目倒计时时间
    int questionNumber = 4; // 题目总数量
    int currentQuestionNumber = 0; // 当前题目下标
    QuestionOptionListAdapter optionAdapter; // 选项适配器
    MyCountDownTimer questionCountDownTimer; // 题目倒计时显示和控制

    AnswerQuestionBean answerQuestionBean; // 提交答案上传的对象，包含所有题
    List<AnswerQuestionBean.AnswerListBean> answerListBeans; // 回答的每一题的详情集合
    AnswerQuestionBean.AnswerListBean answerListBean;  // 回答的每一题的详情对象
    List<String> submitAnswers; // 回答的每一题的详情对象中回答的选项列表

    Handler handler;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_answer_question;
    }

    @Override
    protected void initViews() {
        // 界面总倒计时时长 = 题数 * (每一道题计时时长 + 5)  每道题富余5秒钟时长
        startCountdownTimer(questionNumber * (questionTime + 5), null, null);
    }

    @Override
    protected void initData() {

        String openId = ShareUtils.getInstance().getString(ShareKey.QUESTION_UID);
        if (TextUtils.isEmpty(openId)) {
            showErrorTip("获取到的数据为空");
            startCountdownTimer(3, null, null);
            return;
        }

        showProgressDialog("正在加载题目，请稍后...");
        QuestionHttpTools.getQuestion(this);

    }

    @Override
    public void doEventBusResult(MsgEventBus event) {

    }

    @OnClick({R.id.answerQuestion_goBack_btn, R.id.answerQuestion_nextQuestion_btn})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.answerQuestion_goBack_btn:
                new CustomDialog.Builder(this)
                        .setTitle("操作确认")
                        .setMessage("确认放弃后续的答题并直接退出？\n注：放弃后之前回答的题目将会作废")
                        .setNegativeButton("确认退出", (dialog, which) -> {
                            startCountdownTimer(0, null, null);
                        })
                        .setPositiveButton("继续答题", null)
                        .create().show();
                break;
            case R.id.answerQuestion_nextQuestion_btn: // 跳转到下一题
                nextQuestionBtn.setEnabled(false);
                // 取消题目的倒计时
                questionCountDownTimer.cancel();

                // 答题-4 将之前选择的选项转成int元素的List
                List<Integer> answers = new ArrayList<>();
                for (String answerStr : submitAnswers) {
                    answers.add(Integer.parseInt(answerStr));
                }
                // 将选中的答案设置到题的详情对象中
                answerListBean.setSubmit_answer(answers);
                // 将设置好的题的对象添加到题目列表中
                answerListBeans.add(answerListBean);

                nextQuestion();
                break;
        }
    }

    private void nextQuestion() {

        // 获取题目，并对题目中选项数据进行判断
        QuestionBean questionBean = questionList.get(currentQuestionNumber);
        String answerValue = questionBean.getAnswer_value();
        answerValue = answerValue.replace(",", "");

        StringBuilder answerSb = new StringBuilder();
        for (QuestionBean.OptionsBean optionsBean : questionBean.getOptions()) {
            if (optionsBean.isSelect()) {
                answerSb.append(optionsBean.getSort());
            }
        }

        L.iTag("确认答案", String.format("answerValue:%s, answerSb:%s", answerValue, answerSb.toString()));

        // 展示回答结果正确还是错误
        showRightResultToast(answerValue.equals(answerSb.toString()));
//        if (answerValue.equals(answerSb.toString())) {
//            showRightTip("回答正确");
//        } else {
//            showErrorTip("回答错误");
//        }

        handler = new Handler();
        handler.postDelayed(() -> {
            // 检查是否是最后一题，如果是最后一题了，那么就提交答案
            if (currentQuestionNumber >= questionList.size() - 1) {
                // 答题-5 提交答案之前把前面设置好的List设置到提交的对象中
                answerQuestionBean.setAnswer_list(answerListBeans);

                showProgressDialog("正在提交答案....");
                QuestionHttpTools.submitAnswer(answerQuestionBean, AnswerQuestionActivity.this);
                return;
            }

            // 展示下一题
            setShowQuestion(++currentQuestionNumber);
        }, 2000);

    }

    /**
     * 设置显示的问题
     *
     * @param index 设置的对象下标
     */
    private void setShowQuestion(int index) {

        if (questionList != null && questionList.size() > 0 && index >= 0 && index < questionList.size()) {
            QuestionBean currentQuestionBean = questionList.get(index);
            boolean isSingle = currentQuestionBean.getQuestion_type() != 1; // 是否是单选

            // 答题-2 创建一个当前题目的对象 并设置上题目的id和题目编号
            answerListBean = new AnswerQuestionBean.AnswerListBean();
            answerListBean.setQuestion_id(currentQuestionBean.getQuestion_id());
            answerListBean.setQuestion_index(currentQuestionBean.getQuestion_index());
            submitAnswers = new ArrayList<>(); // 创建一个答案的集合，选项点击的时候直接将下标转为String放进来

            questionNumberTv.setText(String.format(Locale.ENGLISH, "【%d/%d题】", index + 1, questionNumber));
            questionTypeTv.setText(currentQuestionBean.getQuestion_type_str());
            questionStemTv.setText(String.format("\u0003\u0003\u0003\u0003\u0003\u0003%s", currentQuestionBean.getQuestion_content()));
            if (optionAdapter == null) {
                optionAdapter = new QuestionOptionListAdapter(this, currentQuestionBean.getOptions(), currentQuestionBean.getQuestion_type() != 1);
                optionAdapter.setOnItemSelectedListener((i, isSelected, sortStr) -> {
                    // 答题-3 添加或者删除点击的选项中sort字段 下一步在按钮点击方法中
                    if (isSelected) {
                        if (isSingle) { // 单选
                            submitAnswers.clear();
                        }
                        submitAnswers.add(sortStr); // 此处添加和删除String格式的不会误以下标删除导致报错
                    } else {
                        submitAnswers.remove(sortStr);
                    }
                    String logStr = "选择下标:" + submitAnswers.toString();
                    if (submitAnswers.size() > 0) {
                        L.i(logStr);
                    } else {
                        L.e(logStr);
                    }
                });
                questionOptionRecv.setLayoutManager(new LinearLayoutManager(this));
                questionOptionRecv.setAdapter(optionAdapter);

            } else {
                optionAdapter.setList(currentQuestionBean.getOptions(), currentQuestionBean.getQuestion_type() != 1);
            }

            // 设置缩放动画
            setAnimation();

            if (index == questionList.size() - 1) {
                nextQuestionBtn.setText("完成");
            }
        }

        L.i("开始展示题目的倒计时");
        // 题目设置完成，开始展示计时
        questionCountDownTimer.start();

    }

    void setAnimation() {
        ScaleAnimation scaleAnimation = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(300);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                nextQuestionBtn.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        questionOptionRecv.startAnimation(scaleAnimation);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        try {
            JSONObject jsonObject = new JSONObject(requestJsonStr);
            if (requestUrl.endsWith("get_question")) {
                JSONObject dataJSON = jsonObject.optJSONObject("data");
                if (dataJSON == null) {
                    startCountdownTimer(3, null, null);
                    showErrorTip("回传的Data数据格式不正确");
                    return;
                }
                questionTime = dataJSON.getInt("questionTime");
                setShowQuestionTime();
                JSONArray questionsArray = dataJSON.optJSONArray("questions");
                if (questionsArray == null) {
                    startCountdownTimer(3, null, null);
                    showErrorTip("当前没有要回答的题目");
                    return;
                }
                questionList = GsonUtils.jsonArray2ModelList(questionsArray.toString(), QuestionBean.class);
                // 列表中有存在数据
                if (questionList == null || questionList.size() <= 0) {
                    startCountdownTimer(3, null, null);
                    showErrorTip("当前题目列表为空");
                    return;
                }
                questionNumber = questionList.size();
                // 答题-1 创建上传答案的对象并设置基础字段的值
                answerQuestionBean = new AnswerQuestionBean();
                answerQuestionBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID)); // MchId 机器启动的时候请求到的
                answerQuestionBean.setOpen_id(ShareUtils.getInstance().getString(ShareKey.QUESTION_UID)); // 答题人的ID 登录的时候回传
                answerListBeans = new ArrayList<>(); // 题目的集合
                setShowQuestion(currentQuestionNumber);
                return;
            }
            if (requestUrl.endsWith("/submit_answer")) {
                ResultAnswerBean resultAnswerBean = GsonUtils.json2Model(jsonObject.optString("data"), ResultAnswerBean.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("resultAnswer", resultAnswerBean);
                startActivity(AnswerRequestActivity.class, bundle);
                finish();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置题目展示时间长度
     */
    private void setShowQuestionTime() {
        questionCountDownTimer = new MyCountDownTimer(questionTime * 1000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                questionTimeTv.setText(new StringBuffer().append(millisUntilFinished / 1000).append("s"));
            }

            @Override
            public void onFinish() {
                nextQuestionBtn.performClick();
            }
        };
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        startCountdownTimer(3, null, null);
        showErrorTip(errorMsg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (questionCountDownTimer != null) {
            questionCountDownTimer.cancel();
            questionCountDownTimer = null;
        }
    }

    AnswerResultToast answerResultToast;

    /**
     * 展示回答完成的弹窗
     *
     * @param isRight 是否展示回答正确的弹窗
     */
    void showRightResultToast(boolean isRight) {
        if (answerResultToast != null) {
            answerResultToast.cancel();
            answerResultToast = null;
        }
        answerResultToast = AnswerResultToast.makeText(this, 2000);
        answerResultToast.setIcon(isRight ? R.drawable.img_answer_right : R.drawable.img_answer_error);
        answerResultToast.show();
    }

}
